/**
 * 清除PWA缓存和Service Worker的工具函数
 */

export const clearPWACache = async (): Promise<void> => {
  try {
    // 1. 清除所有缓存
    if ('caches' in window) {
      const cacheNames = await caches.keys();
      console.log('找到缓存:', cacheNames);
      
      await Promise.all(
        cacheNames.map(cacheName => {
          console.log('删除缓存:', cacheName);
          return caches.delete(cacheName);
        })
      );
      console.log('所有缓存已清除');
    }

    // 2. 注销所有Service Worker
    if ('serviceWorker' in navigator) {
      const registrations = await navigator.serviceWorker.getRegistrations();
      console.log('找到Service Worker注册:', registrations.length);
      
      await Promise.all(
        registrations.map(registration => {
          console.log('注销Service Worker:', registration.scope);
          return registration.unregister();
        })
      );
      console.log('所有Service Worker已注销');
    }

    // 3. 清除localStorage中的认证状态
    const authStorageKey = 'auth-store';
    if (localStorage.getItem(authStorageKey)) {
      console.log('清除本地存储的认证状态');
      localStorage.removeItem(authStorageKey);
    }

    console.log('PWA缓存清理完成，请刷新页面');
    
  } catch (error) {
    console.error('清除PWA缓存失败:', error);
  }
};

// 在开发模式下添加到全局对象，方便调试
if (process.env.NODE_ENV === 'development') {
  (window as any).clearPWACache = clearPWACache;
}